package Master;

import java.util.LinkedList;
import java.util.Queue;

/*
 * Thread of sending job to worker when job is assigned to that worker
 */
public class WorkerDispatcher extends Thread{
    private final Queue<TaskRunnable> queue;
    private boolean isRunning = true;

    public WorkerDispatcher(){
        queue = new LinkedList<TaskRunnable>();
    }

    public void stopRunning(){
        this.isRunning = false;
    }

    public void add(TaskRunnable task){
        synchronized (queue){
            System.out.println(task.getEstimateTime());
            System.out.println("New task add " + ((Task)task).getTaskID());
            queue.offer(task);
            System.out.println("Queue Size " + queue.size());
            queue.notify();
        }
    }
    
    public void run(){
        TaskRunnable task;
        while (true) {
            synchronized (queue) {

                while (queue.isEmpty()){
                    try {
                        queue.wait();
                    }
                    catch (InterruptedException ignored){

                    }
                }

                task = (TaskRunnable) queue.poll();
                System.out.println("!!!!!!!!!!!!Run Task " + 
                									((Task)task).getTaskID());
                System.out.println("!!!!!!!!!!!!Queue Size " + queue.size());
            }

            try{
                if(task == null){
                    System.out.println("TASK NULL!!!!");
                }
                
                task.run();
            } catch (RuntimeException e) {
                System.out.println("Error happens while dispatcher is "+
                												"running..");
            }
        }
    }

}